<script setup>
import { ref, onMounted } from 'vue'
const isLock = ref(false)
let myVideo = null
let myBox = null
let currentX = null
let currentY = null
let boxW = null
let boxH = null
onMounted(() => {
  myVideo = document.getElementById('myVideo')
  myBox = document.getElementById('myBox')
  boxW = myVideo.clientWidth
  boxH = myVideo.clientHeight
  document.addEventListener('pointerlockchange', lockChangeAlert, false)
})
const updateMousePosition = (event) => {
  console.log(event)
  console.log(event.movementX, event.movementY)
  currentX = currentX + event.movementX
  currentY = currentY + event.movementY
  console.log(currentX, currentY)
  currentX = Math.max(0, Math.min(boxW, currentX))
  currentY = Math.max(0, Math.min(boxH, currentY))
  myBox.style.transform = 'translate(' + currentX + 'px,' + currentY + 'px)'
}
const lockChangeAlert = () => {
  if (
    document.pointerLockElement === myVideo ||
    document.mozPointerLockElement === myVideo ||
    document.webkitPointerLockElement === myVideo
  ) {
    console.log('鼠标锁定')
    isLock.value = true

    myVideo.addEventListener('mousemove', updateMousePosition, false)
  } else {
    console.log('解除鼠标锁定')
    isLock.value = false
    myVideo.removeEventListener('mousemove', updateMousePosition, false)
  }
}

const lockMouse = (event) => {
  if (!isLock.value) {
    myVideo.requestPointerLock()
    if (currentX) return
    currentX = event.offsetX
    currentY = event.offsetY
    myBox.style.transform = 'translate(' + event.offsetX + 'px,' + event.offsetY + 'px)'
  } else {
    console.log('click')
  }
}
</script>
<template>
  <div class="game-wrapper">
    <div
      class="w-[90vw] h-[90vh] bg-[#eee] position top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%] relative my-cursor"
      @click="lockMouse"
      id="myVideo"
    >
      <div
        class="size-[32px] bg-[#999] absolute z-[9] top-0 left-0 pointer-events-none"
        id="myBox"
      ></div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.game-wrapper {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-image: url('https://start.gtimg.com/game/image/1920x1080_1702354161169_1702354164.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
#myBox {
  background: url('');
}
.my-cursor {
  cursor: url('');
}
</style>
